package com.hnqcgczy.sgzShop.db;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import java.sql.Connection;
import java.sql.SQLException;

public class MyTransaction {//事务
    private Connection conn;
    private ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();

    public MyTransaction(boolean isAutoCommit) {
        try {
//            IDb db=new DbImpl();
//            conn=db.getConByMysql();//立即實例化
            conn= comboPooledDataSource.getConnection();
            this.conn.setAutoCommit(isAutoCommit);//属性有可能改变了
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    /**
     * 返回数据库连接对象
     * @return
     */
    public Connection getConnection(){
        return conn;
    }

    /**
     * 关闭数据库  //将数据库连接对象放回连接池
     * @throws SQLException
     */
    public void closeConn() throws SQLException {

        comboPooledDataSource.close();
//        if(conn!=null&&!conn.isClosed()){
//            conn.close();
//
//        }
    }

    public void commit(){
        if(conn!=null){
            try {
                conn.commit();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }


    public void rollback(){
        if(conn!=null){
            try {
                conn.rollback();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }

    }

    public static void main(String[] args) {
        MyTransaction myTransaction = new MyTransaction(true);
        try {
            System.out.println(myTransaction.getConnection().isClosed());
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

}
